package cn.inno.util;

import cn.inno.entitys.ErrorMsg;
import cn.inno.exceptions.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class BaseUtil {

    protected static final String KEY_DATA = "data";
    protected static final String KEY_TOTALT = "total";
    protected static final String KEY_PAGES = "pageNums";

    @Autowired
    private RedisTemplate redisTemplate;

    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    protected HttpServletResponse getResponse() {
        return ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    protected Object getObject(String attrName) {
        ValueOperations valueOperations = this.redisTemplate.opsForValue();
        return valueOperations.get(this.getRequest().getSession().getId() + attrName);
    }

    protected void setObject(String attrName, Object obj) {
        ValueOperations valueOperations = this.redisTemplate.opsForValue();
        valueOperations.set(this.getRequest().getSession().getId() + attrName, obj);
    }

//    protected Object getObject(String attrName) {
//        Object obj = null;
//        try {
//            obj = this.getRequest().getSession().getAttribute(attrName);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return obj;
//    }

//    protected void setObject(String attrName, Object obj) {
//        this.getRequest().getSession().setAttribute(attrName, obj);
//    }

    protected Object getAuth() {
        Object object = this.getObject("user");
        if (object == null) {
            throw new BusinessException(ErrorMsg.CALL_FAIL, "权限不足，请切换登陆账号");
        }
        return object;
    }

}